/*
 * Copyright ©2015-2021 Jaemon. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package io.gitee.jaemon.spring.adorner.util;

import io.gitee.jaemon.spring.adorner.exception.AdornerException;

import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * 类工具类
 *
 * @author Jaemon
 * @since 1.0
 */
public class ClassUtils {

    public static final String SPOT = ".";
    public static final String SLANT = "/";

    private ClassUtils() {}


    /**
     * 获取类定义的字段(包括父类)
     *
     * @param clazz
     *      类名
     * @return
     *      字段结果集
     */
    public static List<Field> fields(Class<?> clazz) {
        List<Field> fields = new ArrayList<>();
        fields(clazz, fields, true);
        return fields;
    }

    /**
     * 获取类定义的字段(包括父类)
     *
     * @param clazz
     *      类名
     * @param fields
     *      字段结果集
     */
    public static void fields(Class<?> clazz, List<Field> fields) {
        fields(clazz, fields, true);
    }

    /**
     * 获取类定义的字段(包括父类)
     *
     * @param clazz
     *      类名
     * @param fields
     *      字段结果集
     * @param privately
     *      是否只返回私有字段
     */
    public static void fields(Class<?> clazz, List<Field> fields, boolean privately) {
        Field[] declaredFields = clazz.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            int modifiers = declaredField.getModifiers();
            if (Modifier.isStatic(modifiers) || Modifier.isFinal(modifiers)) {
                continue;
            }

            if (privately && Modifier.isPrivate(modifiers)) {
                fields.add(declaredField);
            }
        }

        if (clazz.getSuperclass() != null && clazz.getSuperclass() != Object.class) {
            fields(clazz.getSuperclass(), fields, privately);
        }
    }

    /**
     * 扫描类
     *
     * @param classNames
     *      类结果存储
     * @param basePackages
     *      包名集合
     */
    public static void doScan(
            List<Class<?>> classNames,
            List<String> basePackages) {
        for (String basePackage : basePackages) {
            scan(classNames, basePackage);
        }
    }


    /**
     * 扫描类
     *
     * @param classNames
     *      类结果存储
     * @param basePackages
     *      包名数组
     */
    public static void doScan(
            List<Class<?>> classNames,
            String... basePackages) {
        for (String basePackage : basePackages) {
            scan(classNames, basePackage);
        }
    }

    /**
     * 扫描类
     *
     * @param classNames
     *      类结果存储
     * @param except
     *      期望的注解 {@link Annotation}
     * @param basePackages
     *      包名数组
     */
    public static void doScan(
            List<Class<?>> classNames,
            Class<? extends Annotation> except,
            String... basePackages) {
        for (String basePackage : basePackages) {
            scan(classNames, basePackage, except);
        }
    }

    /**
     * 扫描类
     *
     * @param classNames
     *      类结果存储
     * @param basePackage
     *      包名
     */
    public static void scan(
            List<Class<?>> classNames,
            String basePackage)
    {
        scan(classNames, basePackage, null);
    }


    /**
     * 扫描类
     *
     * @param classNames
     *      类结果存储
     * @param basePackage
     *      包名
     * @param except
     *      期望的注解 {@link Annotation}
     */
    public static void scan(
            List<Class<?>> classNames,
            String basePackage, Class<? extends Annotation> except)
    {
        try {
            ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
            URL url = classLoader.getResource(basePackage.replace(SPOT, SLANT));
            // packageName is not exist
            if (url == null) {
                return;
            }
            URI uri = url.toURI();
            File file = new File(uri);
            File[] files = file.listFiles();

            for (File f : files) {
                String name = f.getName();

                if (f.isFile()) {
                    String className = basePackage + SPOT + name.substring(0, name.lastIndexOf(SPOT));
                    Class<?> clazz = classLoader.loadClass(className);
                    if (except != null) {
                        boolean exists = AnnotationUtils.classAnnotation(clazz, except);
                        if (exists) {
                            classNames.add(clazz);
                        }
                    } else {
                        classNames.add(clazz);
                    }
                } else {
                    scan(classNames, basePackage + SPOT + name);
                }
            }
        } catch (Exception ex) {
            throw new AdornerException("扫描包=[%s]异常, message=%s", basePackage, ex.getMessage());
        }
    }

    /**
     * 地址集格式化
     *
     * @param urls
     *      地址信息
     * @return
     *      转换后地址
     */
    public static String[] urlsFormat(String[] urls) {
        String[] result = new String[urls.length];
        for (int i = 0; i < urls.length; i++) {
            result[i] = urlFormat(urls[i], true);
        }
        return result;
    }

    /**
     * 地址格式化
     *
     * @param url
     *      地址信息
     * @return
     *      转换后地址
     */
    public static String urlFormat(String url) {
        return urlFormat(url, true);
    }

    /**
     * 地址格式化
     *
     * @param url
     *      地址信息
     * @param prefix
     *      是否前缀处理
     * @return
     *      转换后地址
     */
    public static String urlFormat(String url, boolean prefix) {
        if (StringUtils.isEmpty(url)) {
            return "";
        }
        StringBuilder urlFormat = new StringBuilder();
        if (prefix && !url.startsWith("/")) {
            urlFormat.append("/");
        }
        if (url.endsWith("/")) {
            urlFormat.append(url, 0, url.length() - 1);
        } else {
            urlFormat.append(url);
        }

        return urlFormat.toString();
    }

}
